package com.nmgsr.ptmsapp.utils;


import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;

import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialPort;
import com.hoho.android.usbserial.driver.UsbSerialProber;
import com.hoho.android.usbserial.util.SerialInputOutputManager;
import com.nmgsr.ptmsapp.activity.SingleCameraActivity;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class UsbReaderTool {
    // 在类中新增一个成员变量
    private Context context;
    private static final String ACTION_USB_PERMISSION = "com.example.USB_PERMISSION";
    private static final int BAUD_RATE = 9600; // 根据你的设备调整波特率

    private UsbManager usbManager;
    private UsbSerialDriver serialDriver;
    private UsbDeviceConnection connection;
    private SerialInputOutputManager serialIoManager;
    private final ExecutorService executor = Executors.newSingleThreadExecutor();

    private TextView distanceTextView;

    private final BroadcastReceiver usbReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (ACTION_USB_PERMISSION.equals(action)) {
                synchronized (this) {
                    UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        if (device != null) {
                            setupSerialConnection(device);
                        }
                    } else {
                        Toast.makeText(context, "USB permission denied", Toast.LENGTH_SHORT).show();
                    }
                }
            } else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
                UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                if (device != null && serialDriver != null && device.equals(serialDriver.getDevice())) {
                    disconnectSerial();
                    Toast.makeText(context, "USB设备未链接", Toast.LENGTH_SHORT).show();
                }
            }
        }
    };

    private final Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 0) {
                String distance = (String) msg.obj;
                if (distanceTextView != null) {
                    distanceTextView.setText("Distance: " + distance + " mm");
                }
            }
            return true;
        }
    });

    public UsbReaderTool(Context context, TextView distanceTextView) {
        this.context = context;
        this.usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
        this.distanceTextView = distanceTextView;

        // 注册USB广播接收器
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_USB_PERMISSION);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);

        // 添加 RECEIVER_NOT_EXPORTED 标志
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            context.registerReceiver(usbReceiver, filter, Context.RECEIVER_NOT_EXPORTED);
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.registerReceiver(usbReceiver, filter, Context.RECEIVER_NOT_EXPORTED);
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    public void onResume() {
        // 尝试连接USB设备
        findAndConnectDevice();
    }

    public void onPause() {
        disconnectSerial();
    }

    public void onDestroy() {
        context.unregisterReceiver(usbReceiver);
        disconnectSerial();
    }

    private void findAndConnectDevice() {
        // 查找所有连接的USB设备
        List<UsbSerialDriver> availableDrivers = UsbSerialProber.getDefaultProber().findAllDrivers(usbManager);

        if (availableDrivers.isEmpty()) {
            Toast.makeText(context, "未读取到usb链接设备", Toast.LENGTH_SHORT).show();
            return;
        }

        // 获取第一个设备
        UsbSerialDriver driver = availableDrivers.get(0);
        UsbDevice device = driver.getDevice();

        // 检查权限
        if (!usbManager.hasPermission(device)) {
            // 请求权限
            PendingIntent permissionIntent = PendingIntent.getBroadcast(
                    context, 0, new Intent(ACTION_USB_PERMISSION), PendingIntent.FLAG_IMMUTABLE);
            usbManager.requestPermission(device, permissionIntent);
            return;
        }

        // 已经有权限，直接连接
        setupSerialConnection(device);
    }

    @SuppressLint("WrongConstant")
    private void setupSerialConnection(UsbDevice device) {
        // 查找设备驱动
        List<UsbSerialDriver> availableDrivers = UsbSerialProber.getDefaultProber().findAllDrivers(usbManager);
        for (UsbSerialDriver driver : availableDrivers) {
            if (driver.getDevice().equals(device)) {
                serialDriver = driver;
                break;
            }
        }

        if (serialDriver == null) {
            Toast.makeText(context, "没有找到设备", Toast.LENGTH_SHORT).show();
            return;
        }

        // 打开连接
        connection = usbManager.openDevice(serialDriver.getDevice());
        if (connection == null) {
            Toast.makeText(context, "USB链接失败", Toast.LENGTH_SHORT).show();
            return;
        }

        try {
            // 获取第一个串口端口并打开
            UsbSerialPort port = serialDriver.getPorts().get(0); // 假设只使用第一个端口
            port.open(connection);
            port.setParameters(BAUD_RATE, 8, 1, 0);

            // 发送 "0n" 指令
            byte[] command = "0n".getBytes();
            port.write(command, 1000); // 1000 ms timeout

            // 设置串口数据监听
            serialIoManager = new SerialInputOutputManager(port, new SerialInputOutputManager.Listener() {
                @Override
                public void onNewData(byte[] data) {
                    // 处理接收到的数据
                    String received = new String(data);
                    processDistanceData(received);
                }

                @Override
                public void onRunError(Exception e) {
                    runOnUiThread(() -> {
                        Toast.makeText(context, "Serial connection error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                        disconnectSerial();
                    });
                }
            });

            executor.submit(serialIoManager);
            Toast.makeText(context, "USB device connected", Toast.LENGTH_SHORT).show();

        } catch (IOException e) {
            Toast.makeText(context, "Error setting up serial: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            disconnectSerial();
        }
    }

    private void processDistanceData(String data) {
        try {
            String[] parts = data.split(":");
            if (parts.length > 1) {
                String distanceStr = parts[1].trim().split(" ")[0];
                Message msg = handler.obtainMessage(0, distanceStr);
                handler.sendMessage(msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void disconnectSerial() {
        if (serialIoManager != null) {
            serialIoManager.stop();
            serialIoManager = null;
        }

        if (serialDriver != null && !serialDriver.getPorts().isEmpty()) {
            try {
                // 关闭所有端口
                for (UsbSerialPort port : serialDriver.getPorts()) {
                    if (port.isOpen()) {
                        port.close();
                    }
                }
            } catch (IOException e) {
                // 忽略关闭端口时的异常
            }
            serialDriver = null;
        }

        if (connection != null) {
            connection.close();
            connection = null;
        }
    }

    private void runOnUiThread(Runnable runnable) {
        ((SingleCameraActivity) context).runOnUiThread(runnable);
    }
}

